<template>
  <div class="relative overflow-hidden">
    <!--  当前没有工序时显示-->
    <div class="no-workshop" v-if="showAddBtn">
      <div class="add-btn cursor-pointer flex justify-center items-center" @click="showWorkShop">
        <div>
          <q-icon name="iconfont icontubiao-39" size="48px"/>
          <div class="margin-t-10">添加</div>
        </div>
      </div>
    </div>
    <div v-else>
      <tabs :tabList="workshopList" v-model="selTab" @addTab="showWorkShop" @deleteTab="deleteTab"/>
      <q-form class="padding-t-20 padding-l-20 flex wrap scroll scrollbar box-wrapper" ref="form">
        <div class="content-wrapper" v-for="(item, index) in cameraIpList" :key="index">
          <div v-if="type===1" class="device ellipsis">设备编号: {{item.deviceCode}}</div>
          <div v-if="type===1" class="device">设备名称: {{item.deviceName}}</div>
          <div v-if="type===2" class="device">车间名称: {{item.workshopName}}</div>
          <div class="divider"/>
          <div class="ip">IP地址:</div>
          <q-input
            v-model.trim="item.cameraIp"
            dense
            outlined
            clearable
            maxlength="100"
            :rules="[
              val => val && validateIp(val) || '请输入合法ip地址或域名'
            ]"
            class="q-field--with-bottom"
            placeholder="请输入IP地址"
          >
          </q-input>
          <q-icon class="close fr font-size-16" name="iconfont icontubiao-67" @click="deleteDevice(index, item.id)" />
        </div>
      </q-form>
      <div class="flex justify-center btn-container" style="padding-top: 10px">
        <div>
          <q-btn class="btn margin-r-10" outline color="primary" label="返回" @click="$emit('back')"/>
          <q-btn class="btn margin-r-10" outline color="primary" label="添加" @click="addDeviceSetDialog"/>
          <q-btn class="btn margin-r-10" outline color="primary" :disable="cameraIpList.length === 0" label="恢复默认" @click="resetDevice"/>
          <q-btn class="btn" unelevated color="primary" :disable="cameraIpList.length === 0 || disableSave" label="保存" @click="saveDevice"/>
        </div>
      </div>
    </div>
    <add-device ref="addDevice" :type="type" :workshopList="workshopList" @selectWorkshop="selectWorkshop"/>
    <add-set ref="addSet" @success="selectDevice" :workshopName="workshopName"/>
    <add-device-set ref="addDeviceSet" :type="type" :workshop="selTab" :workshopName="workshopName" :selDevice="cameraIpList" @success="selectDevice"/>
  </div>
</template>

<script>
import addDevice from './add-device'
import addDeviceSet from './add-device-set'
import addSet from './add-set'
import tabs from 'src/components/tab'
import {
  addCamera,
  addDeviceCamera, deleteCamera, deleteCameraById, deleteDeviceCamera, getCameraConfig, getCameraConfigSet,
  getDeviceCameraConfig,
  getDeviceCameraConfigSet, getNotSetDeviceCamera
} from '../../../../boot/status-monitor/machine'

export default {
  name: 'equipment-config',
  props: {
    type: {
      type: Number,
      default: 1
    }
  },
  components: {
    addDevice,
    addDeviceSet,
    addSet,
    tabs
  },
  data () {
    return {
      workshopList: null,
      cameraIpList: [],
      selTab: null,
      planNumber: '',
      addCount: 0,
      initAdd: false,
      lineId: '',
      disableSave: false
    }
  },
  computed: {
    showAddBtn () {
      return this.workshopList && this.workshopList.length === 0
    },
    workshopName () {
      if (!this.workshopList) {
        return ''
      }
      const workshopInfo = this.workshopList.find(item => item.name === this.selTab)
      if (workshopInfo) {
        return workshopInfo.label
      }
      return ''
    }
  },
  watch: {
    selTab (val) {
      if (val) {
        if (this.initAdd) {
          this.initAdd = false
          this.getAllCamera()
        } else {
          this.getSetCamera(val)
        }
      }
    }
  },
  created () {
    this.getWorkShop()
  },
  methods: {
    // 显示添加设备弹框
    showWorkShop () {
      this.$refs.addDevice.showDialog()
    },
    // 获取已配置摄像头的车间
    getWorkShop (selTab = null) {
      // 如果是按设备
      if (this.type === 1) {
        getDeviceCameraConfig().then(res => {
          this.workshopList = res.data.map(item => {
            return {
              name: item.workshopId,
              label: item.workshopName
            }
          })
          this.selTab = selTab === null ? this.workshopList.length > 0 ? this.workshopList[0].name : null : selTab
        })
      } else {
        // 按车间配置
        getCameraConfig().then(res => {
          this.workshopList = res.data.map(item => {
            return {
              name: item.workshopId,
              label: item.workshopName
            }
          })
          this.selTab = selTab === null ? this.workshopList.length > 0 ? this.workshopList[0].name : null : selTab
        })
      }
    },
    // 删除车间下的所有摄像头
    deleteTab (data) {
      this.$utils.showMessage('icontubiao-28', '确认删除此车间摄像头配置吗？', () => {
        this.$q.loading.show()
        const index = this.workshopList.findIndex(item => item.name === data.name)
        if (this.type === 1) {
          deleteDeviceCamera(data.name).then(res => {
            if (res.code + '' === '1200') {
              this.workshopList.splice(index, 1)
              if (index > 0) {
                this.selTab = this.workshopList[index - 1].name
              } else if (index === 0) {
                this.selTab = this.workshopList.length > 0 ? this.workshopList[0].name : null
              }
              this.$message.success('操作成功')
            }
          }).finally(() => {
            this.$q.loading.hide()
          })
        } else {
          deleteCamera(data.name).then(res => {
            if (res.code + '' === '1200') {
              this.workshopList.splice(index, 1)
              this.selTab = this.workshopList.length > 0 ? this.workshopList[0].name : null
              this.$message.success('操作成功')
            }
          }).finally(() => {
            this.$q.loading.hide()
          })
        }
      }, true)
    },
    // 删除单个摄像头
    deleteDevice (index, id) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要删除这条吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          if (id) {
            this.$q.loading.show()
            deleteCameraById(id).then(res => {
              this.cameraIpList.splice(index, 1)
            }).finally(() => {
              this.$q.loading.hide()
            })
          } else {
            this.cameraIpList.splice(index, 1)
          }
        })
    },
    // 点击添加设备确认
    selectWorkshop (params) {
      this.workshopList.push({
        name: params.workshop,
        label: params.workshopName
      })
      this.lineId = params.lineId
      if (this.type === 1) {
        this.initAdd = true
      }
      this.selTab = params.workshop
      if (this.type === 2 && params.count > 0) {
        this.addCount = Number(params.count)
      }
    },
    // 点击添加具体设备确认
    selectDevice (params) {
      if (this.type === 1) {
        this.cameraIpList.push({
          cameraIp: '',
          deviceCode: params.assetNumber,
          deviceId: params.id,
          deviceName: params.name
        })
      } else {
        const count = Number(params)
        for (let i = 0; i < count; i++) {
          this.cameraIpList.push({
            cameraIp: '',
            workshopName: this.workshopName
          })
        }
      }
    },
    // 获取该车间下，已经设置的摄像头
    getSetCamera (workshopId) {
      this.$q.loading.show()
      if (this.type === 1) {
        getDeviceCameraConfigSet(workshopId).then(res => {
          this.cameraIpList = res.data
          if (this.cameraIpList.length === 0) {
            this.getAllCamera()
          }
        }).finally(() => {
          this.$q.loading.hide()
        })
      } else {
        getCameraConfigSet(workshopId).then(res => {
          this.cameraIpList = res.data
          // 如果填写了需要增加的数量
          if (this.addCount > 0) {
            for (let i = 0; i < this.addCount; i++) {
              this.cameraIpList.push({
                cameraIp: '',
                workshopName: this.workshopName
              })
            }
            this.addCount = 0
          }
        }).finally(() => {
          this.$q.loading.hide()
        })
      }
    },
    // 获取所有未配置的摄像头
    getAllCamera () {
      const params = {
        workshopId: this.selTab,
        lineId: this.lineId === 'all' ? '' : this.lineId
      }
      this.$q.loading.show()
      getNotSetDeviceCamera(params).then(res => {
        const params = res.data
        this.cameraIpList = params.map(item => ({
          cameraIp: '',
          deviceCode: item.assetNumber,
          deviceId: item.id,
          deviceName: item.deviceTypeName
        }))
      }).finally(() => {
        this.$q.loading.hide()
      })
    },
    // 显示添加具体设备弹框
    addDeviceSetDialog () {
      if (this.type === 1) {
        this.$refs.addDeviceSet.showDialog()
      } else {
        this.$refs.addSet.showDialog()
      }
    },
    // 保存新增或编辑的摄像头
    saveDevice () {
      this.$refs.form.validate(true).then(result => {
        if (result) {
          this.disableSave = true
          if (this.type === 1) {
            const params = {
              cameras: this.cameraIpList.map(item => ({
                cameraIp: item.cameraIp,
                deviceId: item.deviceId,
                id: item.id ? item.id : ''
              }))
            }
            addDeviceCamera(params).then(res => {
              this.$message.success('保存成功')
              this.getSetCamera(this.selTab)
            }).finally(() => {
              this.disableSave = false
            })
          } else {
            const params = {
              workshopId: this.selTab,
              cameras: this.cameraIpList.map(item => ({
                cameraIp: item.cameraIp,
                id: item.id ? item.id : ''
              }))
            }
            addCamera(params).then(res => {
              this.$message.success('保存成功')
              this.getSetCamera(this.selTab)
            }).finally(() => {
              this.disableSave = false
            })
          }
        }
      })
    },
    // 将所有的摄像头IP设置为空
    resetDevice () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要恢复默认吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          this.cameraIpList.forEach(item => {
            item.cameraIp = ''
          })
        })
    },
    // 验证ip是否合法
    validateIp (val) {
      return /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(val) || /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]):([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/.test(val) || /^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/.test(val)
    }
  }
}
</script>

<style scoped lang="stylus">
.btn.q-btn{
  padding: 0;
  min-height: 32px!important;
  height: 32px!important;
}

.btn-container{
  width: calc(100% - 48px)
  position: absolute
  bottom: 24px
  border-top: 1px solid #d3d3d3
}
.no-workshop{
  margin auto
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 200px)
  .add-btn{
    width 140px
    height 140px
    border-radius 6px
    border 1px dashed #d3d3d3
    font-size 16px
    text-align center
    color #999
    &:hover{
      border-color $primary
      color $primary
      background-color rgba(95, 119, 253, 0.17)
      transition all ease-in .2s
    }
  }
}

.box-wrapper{
  max-height calc(100vh - 272px)
}
.content-wrapper{
  padding 18px 20px 5px 20px;
  width 309px;
  background #FFFFFF;
  box-shadow 0px 0px 7px 0px rgba(22, 22, 22, 0.2);
  opacity 0.94;
  border-radius 6px;
  margin-right 20px
  margin-bottom 20px
  font-size: 16px;
  font-weight: 400;
  position relative;

  .close{
    display none;
    position absolute;
    right 10px;
    top 10px;
    cursor pointer;
    color rgba(0,0,0,0.54)
  }

  .device{
    color: #333333;
  }

  .divider{
    width: 100%;
    height: 1px;
    background: #D3D3D3;
    margin 8px 0
  }

  .ip{
    color: #5F77FD;
  }

  &:hover{
    background: #DFE4FF;
    transition all ease-in .2s;

    .close {
      display block;
    }
  }
}

.btn{
  width: 96px;
  height: 32px;
}
</style>
